<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Plus, Picture, View, Warning, User } from '@element-plus/icons-vue'
import { unionListApi, updateAnchorRationApi, dissolveGuildApi, UnionStatusText, UnionStatusType } from '@/api/union'
import UnionForm from './components/UnionForm.vue'
import CreateUnion from './components/CreateUnion.vue'
import { useRouter } from 'vue-router'
import { useTabsStore } from '@/store/tabs'

const router = useRouter()
const tabsStore = useTabsStore()

// 搜索参数
const searchParams = reactive({
  guildNo: '',
  userNo: '',
  nickName: '',
  pageIndex: 1,
  pageSize: 10
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const totals = ref(0)
const pagination = reactive({
  page: 1,
  pageSize: 10
})

// 加载数据 - 使用GET请求
const loadData = async () => {
  loading.value = true
  try {
    const requestParams = {
      ...searchParams,
      pageIndex: pagination.page,
      pageSize: pagination.pageSize
    }
    
    // 过滤空值
    const filteredParams = Object.fromEntries(
      Object.entries(requestParams).filter(([_, value]) => {
        return value !== '' && value !== null && value !== undefined
      })
    )
    
    const { data } = await unionListApi(filteredParams)
    tableData.value = data.list || []
    totals.value = data.total || 0
  } catch (error) {
    console.error('加载工会列表失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置方法
const handleReset = () => {
  Object.assign(searchParams, {
    guildNo: '',
    nickName: '',
    pageIndex: 1,
    pageSize: 10
  })
  pagination.page = 1
  pagination.pageSize = 10
  loadData()
}

// 分页方法
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadData()
}



// 编辑相关
const unionFormVisible = ref(false)
const isEdit = ref(false)
const currentUnion = ref<any>(null)

// 创建工会相关
const createUnionVisible = ref(false)

// 修改分成比例相关
const ratioDialogVisible = ref(false)
const currentRatioUnion = ref<any>(null)
const newRatio = ref(45)

// 解散工会相关
const dissolveDialogVisible = ref(false)
const currentDissolveUnion = ref<any>(null)

const handleEdit = (row: any) => {
  currentUnion.value = row
  isEdit.value = true
  unionFormVisible.value = true
}

const handleCreateUnion = () => {
  createUnionVisible.value = true
}

const handleFormSuccess = () => {
  loadData()
}

const handleCreateSuccess = () => {
  loadData()
}

const handleEditRatio = (row: any) => {
  currentRatioUnion.value = row
  newRatio.value = row.anchorRation || 45
  ratioDialogVisible.value = true
}

const handleRatioSubmit = async () => {
  try {
    // 构建提交数据
    const submitData = {
      guildNo: currentRatioUnion.value.guildNo,
      anchorRation: newRatio.value
    }
    
    await updateAnchorRationApi(submitData)
    
    ElMessage.success('修改成功')
    ratioDialogVisible.value = false
    loadData()
  } catch (error: any) {
    ElMessage.error(error.message || '修改失败')
  }
}

// 处理解散工会
const handleDissolve = (row: any) => {
  currentDissolveUnion.value = row
  dissolveDialogVisible.value = true
}

// 确认解散工会
const handleDissolveConfirm = async () => {
  try {
    await dissolveGuildApi(currentDissolveUnion.value.guildNo)
    
    ElMessage.success('工会解散成功')
    dissolveDialogVisible.value = false
    loadData()
  } catch (error: any) {
    ElMessage.error(error.message || '解散失败')
  }
}

// 查看公告
const announcementVisible = ref(false)
const currentAnnouncement = ref('')

const handleViewAnnouncement = (announcement: string) => {
  currentAnnouncement.value = announcement
  announcementVisible.value = true
}

// 跳转到成员列表
const handleViewMembers = (row: any) => {
  // 添加成员列表选项卡
  tabsStore.addTab('成员列表', '/union/memberList', 'User')
  
  // 设置当前激活的选项卡
  tabsStore.setCurrentTab('成员列表', '/union/memberList')
  
  // 跳转到成员列表页面
  router.push({
    name: 'memberList',
    query: { guildNo: row.guildNo }
  })
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  loadData()
})
</script>

<template>
  <div class="union-list">
    <!-- 查询区域 -->
    <el-card class="mb">
      <el-form :model="searchParams" inline>
        <el-form-item label="昵称">
          <el-input
            v-model="searchParams.nickName"
            placeholder="请输入昵称"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="工会ID">
          <el-input
            v-model="searchParams.guildNo"
            placeholder="请输入工会ID"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleCreateUnion">
            <el-icon><Plus /></el-icon>
            创建公会
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        :fit="true"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column type="index" label="序号" min-width="60" align="center" />
        <el-table-column label="公会头像" min-width="100" align="center">
          <template #default="{ row }">
            <el-image
              :src="row.avatar"
              :preview-src-list="[row.avatar]"
              fit="cover"
              style="width: 50px; height: 50px; border-radius: 50%; cursor: pointer;"
              :initial-index="0"
              preview-teleported
            >
              <template #error>
                <el-avatar :size="50">
                  <el-icon><Picture /></el-icon>
                </el-avatar>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="公会信息" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="union-info">
              <div class="union-name">昵称: {{ row.name || '-' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="guildNo" label="公会ID" min-width="120" show-overflow-tooltip />
        <el-table-column label="会长" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="owner-info" v-if="row.user">
              <div class="owner-name">昵称: {{ row.user.nickname || '-' }}</div>
              <div class="owner-id">ID: {{ row.user.userNo || '-' }}</div>
            </div>
            <div class="owner-info" v-else>
              <div class="owner-name">昵称: -</div>
              <div class="owner-id">ID: -</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="公会手机号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="ownerUserNo" label="会长ID" min-width="120" show-overflow-tooltip />
<!--        <el-table-column label="主播分成比例" min-width="120" align="center">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleEditRatio(row)"
              style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none;"
            >
              {{ row.anchorRation || 0 }}%
            </el-button>
          </template>
        </el-table-column>-->
        <el-table-column label="公告" min-width="150">
          <template #default="{ row }">
            <div v-if="row.announcement" class="announcement-cell">
              <span class="announcement-text">{{ row.announcement }}</span>
              <el-button 
                type="info" 
                size="small" 
                @click="handleViewAnnouncement(row.announcement)"
                style="margin-left: 8px; padding: 4px 8px; background: linear-gradient(135deg, #ff9500, #ffb74d); border: none;"
              >
                <el-icon><View /></el-icon>
              </el-button>
            </div>
            <span v-else class="no-announcement">-</span>
          </template>
        </el-table-column>
        <el-table-column label="成员数量" min-width="100" align="center">
          <template #default="{ row }">
            <span class="member-count">{{ row.memberCount }}人</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag type="success" size="small">
              {{ UnionStatusText[row.status] || '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160" show-overflow-tooltip>
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="管理" min-width="200" align="center">
          <template #default="{ row }">
            <el-button type="info" size="small" @click="handleViewMembers(row)">
              <el-icon><User /></el-icon>
              成员列表
            </el-button>
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDissolve(row)">
              解散
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination 
        class="pagination-center mt"
        v-model:current-page="pagination.page" 
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]" 
        layout="total, sizes, prev, pager, next, jumper" 
        :total="totals" 
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" 
        background
      />
    </el-card>



    <!-- 公告查看弹窗 -->
    <el-dialog
      v-model="announcementVisible"
      title="工会公告"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="announcement-content">
        <p>{{ currentAnnouncement }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="announcementVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 工会表单弹窗 -->
    <UnionForm
      v-model:visible="unionFormVisible"
      :is-edit="isEdit"
      :union-data="currentUnion"
      @success="handleFormSuccess"
    />

    <!-- 创建工会侧边栏 -->
    <CreateUnion
      v-model:visible="createUnionVisible"
      @success="handleCreateSuccess"
    />

    <!-- 修改分成比例弹窗 -->
    <el-dialog
      v-model="ratioDialogVisible"
      title="修改主播分成比例"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="ratio-dialog-content">
        <p class="ratio-info">
          工会：{{ currentRatioUnion?.name || '-' }}
        </p>
        <el-form label-width="120px">
          <el-form-item label="主播分成比例">
            <el-input-number
              v-model="newRatio"
              :min="0"
              :max="100"
              placeholder="请输入分成比例"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="ratioDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRatioSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 解散工会确认弹窗 -->
    <el-dialog
      v-model="dissolveDialogVisible"
      title="解散工会"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="dissolve-dialog-content">
        <div class="warning-icon">
          <el-icon size="48" color="#f56c6c"><Warning /></el-icon>
        </div>
        <div class="dissolve-info">
          <h3>确认解散工会？</h3>
          <p class="union-detail">
            工会名称：<strong>{{ currentDissolveUnion?.name || '-' }}</strong>
          </p>
          <p class="union-detail">
            工会ID：<strong>{{ currentDissolveUnion?.guildNo || '-' }}</strong>
          </p>
          
          <!-- 详细说明 -->
          <div class="dissolve-description">
            <p class="main-message">
              确认要除此公会吗?删除会解散公会,相关的公会成员也会全部解散。公会入口会变更为公会列表。
            </p>
            <p class="reminder-message">
              提醒:确认解散后会发送文本告知会长及成员,公会已解散
            </p>
          </div>
          
          <div class="warning-text">
            <el-icon><Warning /></el-icon>
            解散后无法恢复，请谨慎操作！
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dissolveDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleDissolveConfirm">确认解散</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="less" scoped>
.union-list {
  .mb {
    margin-bottom: 20px;
  }
  
  .mt {
    margin-top: 20px;
  }
  
  .pagination-center {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .union-info {
    .union-name {
      font-weight: 500;
      margin-bottom: 6px;
      font-size: 16px;
    }
  }

  .owner-info {
    .owner-name {
      font-weight: 500;
      margin-bottom: 2px;
      font-size: 16px;
    }
    
    .owner-id {
      font-size: 14px;
      color: #909399;
    }
  }

  .announcement-cell {
    display: flex;
    align-items: center;
    
    .announcement-text {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 14px;
    }
  }

  .no-announcement {
    color: #909399;
    font-size: 14px;
  }

  .announcement-content {
    max-height: 400px;
    overflow-y: auto;
    padding: 10px;
    background: #f8f9fa;
    border-radius: 4px;
    
    p {
      margin: 0;
      line-height: 1.6;
      font-size: 14px;
      white-space: pre-wrap;
      word-break: break-word;
    }
  }

  .ratio-dialog-content {
    padding: 20px 0;
    
    .ratio-info {
      margin-bottom: 20px;
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }

  .member-count {
    color: #303133;
    font-weight: 500;
    font-size: 14px;
  }

  .dissolve-dialog-content {
    text-align: center;
    padding: 20px 0;
    
    .warning-icon {
      margin-bottom: 20px;
    }
    
    .dissolve-info {
      h3 {
        color: #303133;
        font-size: 18px;
        margin-bottom: 16px;
        font-weight: 600;
      }
      
      .union-detail {
        color: #606266;
        font-size: 14px;
        margin-bottom: 8px;
        line-height: 1.6;
        
        strong {
          color: #303133;
          font-weight: 600;
        }
      }
      
      .dissolve-description {
        margin: 20px 0;
        padding: 16px;
        background: #fff7e6;
        border: 1px solid #ffd591;
        border-radius: 6px;
        
        .main-message {
          color: #d46b08;
          font-size: 14px;
          line-height: 1.6;
          margin-bottom: 12px;
          font-weight: 500;
        }
        
        .reminder-message {
          color: #d46b08;
          font-size: 13px;
          line-height: 1.5;
          margin: 0;
          opacity: 0.9;
        }
      }
      
      .warning-text {
        color: #f56c6c;
        font-size: 14px;
        margin-top: 16px;
        padding: 12px;
        background: #fef0f0;
        border: 1px solid #fbc4c4;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .el-icon {
          margin-right: 6px;
          font-size: 16px;
        }
      }
    }
  }
}
</style>